package at.jku.se.fastsell.app;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import at.jku.se.fastsell.app.R;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
import at.jku.se.fastsell.data.Auction;
import at.jku.se.fastsell.data.Item;
import at.jku.se.fastsell.rest.RestAccess;
import at.jku.se.fastsell.rest.ServiceException;

public class Detail extends Activity {
	private static Auction auctionItem;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);
		auctionItem = (Auction) getIntent().getSerializableExtra(MainActivity.SER_KEY);

		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_overview) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		} else if (id == R.id.action_logout) {
			Session.currentUser = null;
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
		} else if (id == R.id.action_refresh) {
			Intent intent = new Intent(this, Detail.class);
			Bundle mBundle = new Bundle();
			mBundle.putSerializable(MainActivity.SER_KEY, auctionItem);
			intent.putExtras(mBundle);
			startActivity(intent);
		} else if (id == R.id.action_newAuction) {
			Intent intent = new Intent(this, CreateAuctionActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			final View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

			if (auctionItem != null) {
				Button b = (Button) rootView.findViewById(R.id.detailItem_button);
				TextView txtcurrPrice = (TextView) rootView.findViewById(R.id.detailItem_currentPrice);
				final EditText priceField = (EditText) rootView.findViewById(R.id.detailItem_priceField);

				Button button = (Button) rootView.findViewById(R.id.detailItem_button);
				button.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						double inputBid;
						inputBid = Double.parseDouble(priceField.getText().toString());

						if (inputBid <= auctionItem.getCurPrice()) {
							priceField.setError("bid invalid");
						} else if (RestAccess.placeBid(Session.currentUser, auctionItem, inputBid)) {
							try {
								auctionItem = RestAccess.getAuction(auctionItem.getAuctionID());
								Intent intent = new Intent(rootView.getContext(), Detail.class);
								Bundle mBundle = new Bundle();
								mBundle.putSerializable(MainActivity.SER_KEY, auctionItem);
								intent.putExtras(mBundle);
								startActivity(intent);
							} catch (ServiceException e) {
								AlertDialog.Builder ad = new AlertDialog.Builder(v.getContext());
								ad.setCancelable(false);
								ad.setMessage("Could not refresh auction, please try again");
								ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										// TODO
									}
								});
								ad.create().show();
							}
						}
					}
				});

				TextView txtTitle = (TextView) rootView.findViewById(R.id.dateilItem_title);
				TextView txtDesc = (TextView) rootView.findViewById(R.id.detailItem_description);
				TextView from = (TextView) rootView.findViewById(R.id.detailActivity_from);

				txtTitle.setText(auctionItem.getTitle());
				txtDesc.setText(auctionItem.getDescription());
				txtcurrPrice.setText("Euro: " + auctionItem.getCurPrice());
				from.setText("From: " + auctionItem.getSeller());
				priceField.setEnabled(true);
				b.setEnabled(true);
				if (auctionItem.isActive()) {
					SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
					Date currdatTime = new Date(System.currentTimeMillis());
					TextView txtEndDate = (TextView) rootView.findViewById(R.id.detailItem_endDate);
					long offset = 6 * 60 * 60 * 1000;
					if ((currdatTime.getTime() + offset) < auctionItem.getEnd()) {
						long diff = auctionItem.getEnd() - currdatTime.getTime() - offset;
						long diffSeconds = diff / 1000 % 60;
						long diffMinutes = (diff / (60 * 1000)) % 60;
						long diffHours = diff / (60 * 60 * 1000);
						String erg = "";
						if (diffHours > 0) {
							erg = diffHours + " hours ";
						}
						erg = erg + diffMinutes + " minutes and " + diffSeconds + " seconds left";

						if (auctionItem.getBidCount() > 0) {
							erg = erg + "\nHighest Bider: " + auctionItem.getHighestBidder();
						} else {
							erg = erg + "\n without a bid";
						}
						txtEndDate.setText(erg);
					} else {
						if (auctionItem.getBidCount() > 0) {
							txtEndDate.setText("Auction Ended at " + sdf.format(auctionItem.getEnd()) + "\n"
									+ "Highest Bider: " + auctionItem.getHighestBidder());
						} else {
							txtEndDate.setText("Auction Ended at " + sdf.format(auctionItem.getEnd())
									+ " without a bid");
						}
						priceField.setEnabled(false);
						b.setEnabled(false);
					}
				}
			}
			return rootView;
		}
	}

}
